package com.jhgsys.internal.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jhgsys.internal.base.constant.BaseConstants;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.base.dto.BaseGoodsInventoryRecordDto;
import com.jhgsys.internal.base.entity.BaseGoods;
import com.jhgsys.internal.base.entity.BaseGoodsInventoryRecord;
import com.jhgsys.internal.base.service.IBaseGoodsInventoryRecordService;
import com.jhgsys.internal.base.service.IBaseGoodsService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 安全奖品库存记录 Controller
 *
 * @author admin
 * @date 2024-08-06 09:41:00
 */
@Slf4j
@Validated
@Controller
public class BaseGoodsInventoryRecordController extends BaseController {

    @Autowired
    private IBaseGoodsInventoryRecordService baseGoodsInventoryRecordService;

    @Autowired
    private IBaseGoodsService baseGoodsService;



    @GetMapping(FebsConstant.VIEW_PREFIX + "baseGoodsInventoryRecord")
    @RequiresPermissions("baseGoodsInventoryRecord:view")
    public String baseGoodsInventoryRecordIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("base/baseGoodsInventoryRecord/baseGoodsInventoryRecordList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseGoodsInventoryRecord/add")
    @RequiresPermissions("baseGoodsInventoryRecord:add")
    public String baseGoodsInventoryRecordAdd(){
        return FebsUtil.view("base/baseGoodsInventoryRecord/baseGoodsInventoryRecordEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseGoodsInventoryRecord/update/{id}")
    @RequiresPermissions("baseGoodsInventoryRecord:edit")
    public String baseGoodsInventoryRecordUpdate(Model model, @PathVariable("id") String id){
        model.addAttribute("baseGoodsInventoryRecord", baseGoodsInventoryRecordService.findBaseGoodsInventoryRecordById(id));
        return FebsUtil.view("base/baseGoodsInventoryRecord/baseGoodsInventoryRecordEdit");
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-08-06 09:41:00
     */
    @GetMapping("baseGoodsInventoryRecord")
    @ResponseBody
    @RequiresPermissions("baseGoodsInventoryRecord:view")
    public FebsResponse getAllBaseGoodsInventoryRecords(BaseGoodsInventoryRecord baseGoodsInventoryRecord) {
        return new FebsResponse().success().data(baseGoodsInventoryRecordService.findBaseGoodsInventoryRecordList(baseGoodsInventoryRecord));
    }

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-08-06 09:41:00
     */
    @GetMapping("baseGoodsInventoryRecord/list")
    @ResponseBody
    @RequiresPermissions("baseGoodsInventoryRecord:view")
    public FebsResponse baseGoodsInventoryRecordList(QueryRequest request, BaseGoodsInventoryRecordDto baseGoodsInventoryRecord) {
        IPage<BaseGoodsInventoryRecordDto> page = this.baseGoodsInventoryRecordService.findBaseGoodsInventoryRecordDtoPage(request, baseGoodsInventoryRecord);
        return new FebsResponse().success().data(getDataTable(page));
    }

    /**
     * 新增 BaseGoodsInventoryRecord
     * @author admin
     * @date 2024-08-06 09:41:00
     */
    @Log("新增BaseGoodsInventoryRecord")
    @PostMapping("baseGoodsInventoryRecord")
    @ResponseBody
    @RequiresPermissions("baseGoodsInventoryRecord:add")
    public FebsResponse addBaseGoodsInventoryRecord(@RequestBody BaseGoodsInventoryRecord baseGoodsInventoryRecord) throws FebsException {
        try {
            BaseGoods goods = baseGoodsService.findBaseGoodsById(baseGoodsInventoryRecord.getGoodsId());
            if(ObjectUtils.isEmpty(goods)){
                return new FebsResponse().fail().message("商品不存在");
            }

            if(BaseConstants.GOODS_OPERATE_TYPE.OUT.equals(baseGoodsInventoryRecord.getOperateType()) && baseGoodsInventoryRecord.getOperateNumber() > goods.getInventory()){
                return new FebsResponse().fail().message("商品数量小于当前库存，出库失败！");
            }
            baseGoodsInventoryRecord.setCreatedBy(getCurrentUser().getUserName());

            this.baseGoodsInventoryRecordService.createBaseGoodsInventoryRecord(goods,baseGoodsInventoryRecord);

            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增BaseGoodsInventoryRecord失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 逻辑删除 BaseGoodsInventoryRecord
     * @author admin
     * @date 2024-08-06 09:41:00
     */
    @Log("逻辑删除BaseGoodsInventoryRecord")
    @GetMapping("baseGoodsInventoryRecord/delete/{id}")
    @ResponseBody
    @RequiresPermissions("baseGoodsInventoryRecord:delete")
    public FebsResponse deleteBaseGoodsInventoryRecord(@PathVariable("id") String baseGoodsInventoryRecordIds) throws FebsException {
        try {
            BaseGoodsInventoryRecord baseGoodsInventoryRecord = new BaseGoodsInventoryRecord();
            baseGoodsInventoryRecord.setDeletedBy(getCurrentUser().getUserName());
            baseGoodsInventoryRecord.setDeletedTime(new Date());
            baseGoodsInventoryRecord.setDeletedFlg(FebsConstant.INVALID);
            this.baseGoodsInventoryRecordService.deleteBaseGoodsInventoryRecord(baseGoodsInventoryRecord,baseGoodsInventoryRecordIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除BaseGoodsInventoryRecord失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
    * 物理删除 BaseGoodsInventoryRecord
    * @author admin
    * @date 2024-08-06 09:41:00
    */
    @Log("物理删除BaseGoodsInventoryRecord")
    @GetMapping("baseGoodsInventoryRecord/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("baseGoodsInventoryRecord:delete")
    public FebsResponse physicallyDeleteBaseGoodsInventoryRecord(@PathVariable("id") String baseGoodsInventoryRecordIds) throws FebsException {
        try {
            this.baseGoodsInventoryRecordService.physicallyDeleteBaseGoodsInventoryRecord(baseGoodsInventoryRecordIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除BaseGoodsInventoryRecord失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 修改 BaseGoodsInventoryRecord
     * @author admin
     * @date 2024-08-06 09:41:00
     */
    @Log("修改BaseGoodsInventoryRecord")
    @PostMapping("baseGoodsInventoryRecord/update")
    @ResponseBody
    @RequiresPermissions("baseGoodsInventoryRecord:edit")
    public FebsResponse updateBaseGoodsInventoryRecord(@RequestBody BaseGoodsInventoryRecord baseGoodsInventoryRecord) throws FebsException {
        try {
            baseGoodsInventoryRecord.setUpdatedBy(getCurrentUser().getUserName());
            this.baseGoodsInventoryRecordService.updateBaseGoodsInventoryRecord(baseGoodsInventoryRecord);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改BaseGoodsInventoryRecord失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 导出 BaseGoodsInventoryRecord的excel
     * @author admin
     * @date 2024-08-06 09:41:00
     */
    @PostMapping("baseGoodsInventoryRecord/excel")
    @ResponseBody
    @RequiresPermissions("baseGoodsInventoryRecord:view")
    public void export(QueryRequest queryRequest, BaseGoodsInventoryRecordDto baseGoodsInventoryRecord, HttpServletResponse response) throws FebsException {
        try {
            List<BaseGoodsInventoryRecord> baseGoodsInventoryRecords = this.baseGoodsInventoryRecordService.findBaseGoodsInventoryRecordPage(queryRequest, baseGoodsInventoryRecord).getRecords();
            ExcelKit.$Export(BaseGoodsInventoryRecord.class, response).downXlsx(baseGoodsInventoryRecords, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }
}
